package com.example.springboot.model;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint("/myWs")
@Component
public class WsServerEndPoint {
    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static final MessageHandler messageHandler = new MessageHandler();

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        log.info("WebSocket is open: {}", session.getRequestURI().getQuery());
    }

    @OnMessage
    public void onMessage(String text, Session session) {
        log.info("Received a message: {}", text);
        messageHandler.handleMessage(text, session);
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        log.info("WebSocket is closed: {}", session.getRequestURI().getQuery());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket error", error);
    }
}
